package com.shuai.api_platform.utils;

import com.shuai.api_platform.constant.EmailConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class EmailCodeUtils {
    private static final String EMAIL_PATTERN = "^[\\w\\.-]+@[\\w\\.-]+\\.\\w{2,}$";

    public static boolean validateFormat(String email) {
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }


    private static final Random RANDOM = new Random();

    public static String generateCode() {
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < EmailConstant.DIGIT; i++) {
            code.append(RANDOM.nextInt(10));
        }
        return code.toString();
    }

    public static boolean compare(String emailCode, String inputCode) {
        if (StringUtils.isBlank(inputCode) || inputCode.length() != EmailConstant.DIGIT) {
            return false;
        }
        return emailCode.equals(inputCode);
    }
}
